package com.easydev.faseboot.taskfilter.task;

import com.easydev.faseboot.taskfilter.enumeration.ErrorEnum;
import com.easydev.faseboot.taskfilter.filter.TaskFilter;
import com.easydev.faseboot.taskfilter.request.BaseRequest;
import com.easydev.faseboot.taskfilter.response.BaseResponse;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

public class Task<T extends BaseRequest, U extends BaseResponse> {
    List<TaskFilter<T, U>> taskTaskFilters = new ArrayList<>();

    @SuppressWarnings("unchecked")
    public void excute(T request, U response) {
        if (taskTaskFilters.size() == 0 || request == null || response == null) {
            return;
        }
        for (TaskFilter taskFilter : taskTaskFilters) {
            try {
                boolean b = taskFilter.doFilter(request, response);
                if (b) {
                    return;
                }
            } catch (Exception e) {
                StringBuilder sb = new StringBuilder();
                Arrays.stream(e.getStackTrace()).forEach(x -> sb.append(x.toString()));
                response.error(ErrorEnum.SYSTEM_ERROR.getCode(), ErrorEnum.SYSTEM_ERROR.getMsg(), sb.toString());
                break;
            }
        }
    }

    public void add(TaskFilter taskFilter) {
        taskTaskFilters.add(taskFilter);
    }
}